package chen.yi.component.common.comparator;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 比较两个实体类属性值
 *
 * @author huat
 **/
public final class EntityComparator {
    private EntityComparator() {
    }

    /**
     * 获取两个对象相同的属性值
     * @param obj1 对象1
     * @param obj2 对象2
     * @param ignoreCase 是否忽略大小写
     * @return 相同属性名和值的Map
     */
    public static Map<String, Object> intersectEntity(Object obj1, Object obj2,boolean ignoreCase)
            throws IllegalAccessException {
        validateInput(obj1, obj2);
        Map<String, Object> result = new LinkedHashMap<>();

        for (Field field : getAllFields(obj1.getClass())) {
            field.setAccessible(true);
            Object value1 = field.get(obj1);
            Object value2 = field.get(obj2);

            if (ignoreCase && value1 instanceof String && value2 instanceof String) {
                if (((String) value1).equalsIgnoreCase((String) value2)) {
                    result.put(field.getName(), value1);
                }
            } else if (Objects.equals(value1, value2)) {
                result.put(field.getName(), value1);
            }
        }
        return result;
    }

    /**
     * 比较两个对象不相等的属性
     * @param target 目标对象
     * @param source 比较对象
     * @param ignoreCase 忽略大小写
     * @return 差异属性名和值的Map
     */
    public static Map<String, Object> differenceEntity(Object target, Object source,boolean ignoreCase)
            throws IllegalAccessException {
        validateInput(target, source);
        Map<String, Object> result = new LinkedHashMap<>();

        for (Field field : getAllFields(target.getClass())) {
            field.setAccessible(true);
            Object targetValue = field.get(target);
            Object sourceValue = field.get(source);

            if (ignoreCase && targetValue instanceof String && sourceValue instanceof String) {
                if (!((String) targetValue).equalsIgnoreCase((String) sourceValue)) {
                    result.put(field.getName(), sourceValue);
                }
            } else if (!Objects.equals(targetValue, sourceValue)) {
                result.put(field.getName(), sourceValue);
            }
        }
        return result;
    }

    private static void validateInput(Object obj1, Object obj2) {
        if (obj1 == null || obj2 == null) {
            throw new IllegalArgumentException("比较对象不能为null");
        }
        if (!obj1.getClass().equals(obj2.getClass())) {
            throw new IllegalArgumentException("比较对象类型不一致");
        }
    }

    private static List<Field> getAllFields(Class<?> clazz) {
        List<Field> fields = new ArrayList<>();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            Collections.addAll(fields, clazz.getDeclaredFields());
        }
        return fields;
    }
}
